class Memento {
    constructor(state) {
        this.state = state
    }
    getState () {
        return this.state
    }
}

class Originator {
    constructor(state) {
        this.state = state
    }
    setState (state) {
        this.state = state
    }
    createMemento () {
        return new Memento(this.state)
    }
    restoreMemento (memento) {
        this.state = memento.getState()
    }
    getState () {
        return this.state
    }
}

class Caretaker {
    constructor() {
        this.mementos = []
    }
    addMemento (memento) {
        this.mementos.push(memento)
    }
    getMemento (index) {
        return this.mementos[index]
    }
}

const originator = new Originator('state1')
const caretaker = new Caretaker()

caretaker.addMemento(originator.createMemento())

originator.setState('state2')

console.log('originator state: ', originator.getState())

originator.restoreMemento(caretaker.getMemento(0))

console.log('originator state: ', originator.getState())